<template>
   <div>
        <!-- 按钮 -->
         <el-button
            type="primary"
            icon="el-icon-plus"
            style="margin: 10px 0px"
            @click="showDialog"
            >添加</el-button>
       <!-- 表格 
         data:表格显示的数据【数组类型】 
         prop:对应列内容的字段名
       -->
      <el-table style="width: 100%" border :data="list">
          <el-table-column type="index" label="序号" width="80px" align="center">
          </el-table-column>
          <el-table-column prop="tmName" label="品牌名称" width="width">
          </el-table-column>
          <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
            <template slot-scope="{ row, $index }">
               <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
          </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
                    <el-button
                      type="warning"
                      icon="el-icon-edit"
                      size="mini"
                      @click="updateBrand(row)"
                      >修改</el-button
                    >
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="deleteBrand(row)"
                      >删除</el-button
                    >
            </template>
          </el-table-column>
      </el-table>

       <!-- 分页器 -->
       <el-pagination
         style="margin-top: 20px; text-align: center"
         :current-page="page"
         :total="total"
         :page-size="limit"
         :pager-count="7"
         :page-sizes="[3, 5, 10]"
         layout="prev, pager, next, jumper,->,sizes,total"
          @current-change="getPageList"
          @size-change="handleSizeChange"
     >
    </el-pagination>
   
    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
    >
      <!-- form表单 :model属性，这个属性的作用是,把表单的数据收集到哪个对象的身上 ，将来表单验证，也需要这个属性
           rules: 约定的验证规则 
           prop: 设置为需校验的字段名
      -->
      <el-form style="width: 80%" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!--这里收集数据：不能使用v-model，因为不是表单元素
             action:设置图片上传的地址
            :on-success:可以检测到图片上传成功，当图片上传成功，会执行一次
            :before-upload：可以在上传图片之前，会执行一次
          -->
          <el-upload
            class="avatar-uploader"
            action="/product-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateBrand">确 定</el-button>
      </div>
    </el-dialog>

   </div>
</template>

<script>
export default {
    name:'TradeMark',
    data(){
      //自定义校验规则
      var validateTmName = (rule, value, callback) => {
        //自定义校验规则
        if (value.length < 2 || value.length > 10) {
          callback(new Error("品牌名称2-10位"));
        } else {
          callback();
        }
      };
      return {
         //当前页
         page: 1,
         //每页数据条数
         limit: 3,
         //总共数据条数
         total: 0,
         //列表展示的数据
         list: [],
         //对话框显示与隐藏控制的属性
         dialogFormVisible: false,
         tmForm: {
            tmName: "",
            logoUrl: "",
         },
        //表单验证规则
        rules: {
        //品牌名称的验证规则
        //require:必须要校验字段  message 提示信息    trigger:用户行为设置（事件的设置:blur、change）
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          //自定义校验规则
          { validator: validateTmName, trigger: "change" },
        ],
        //品牌的logo验证规则
        logoUrl: [{ required: true, message: "请选择品牌的logo" }],
      },
      }
    },
     
    mounted() {
      //获取列表数据方法
      this.getPageList();
    },
    methods:{
    //获取品牌列表的数据
    async getPageList(currentPage = 1) {
      this.page = currentPage;
      //解构出参数
      const { page, limit } = this;
      let result = await this.$API.brand.reqBrandList(page, limit);
      if (result.code == 200) {
        this.total = result.data.total;
        this.list = result.data.records;
      }
    },
     //当分页器某一页需要展示数据条数发生变化的时候会触发
     handleSizeChange(limit) {
      this.limit = limit;
      this.getPageList();
    },
    //点击添加品牌的按钮
    showDialog() {
      //显示对话框
      this.dialogFormVisible = true;
      //清除数据
      this.tmForm = { tmName: "", logoUrl: "" };
    },
    //图片上传成功
    handleAvatarSuccess(res, file) {
      console.log("图片上传成功！");
      console.log("res=====>",res);
      console.log("file=====>",file);
      this.tmForm.logoUrl = res.data;
    },
    //图片上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
         this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
         this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //添加&修改品牌
    addOrUpdateBrand(){
      this.$refs.ruleForm.validate(async (success) => {
          console.log(success ? "表单验证通过" : "表单验证失败");
          //全部字段符合检验规则
          if(success){
              this.dialogFormVisible = false;  
              console.log("修改品牌====>", this.tmForm);
              let result = await this.$API.brand.reqAddOrUpdateBrand(
                  this.tmForm
              );  
              if(result.code == 200){
                this.$message({
                    type: "success",
                    message: this.tmForm.id ? "修改品牌成功" : "添加品牌成功",
                  });
                  //如果添加品牌：停留在第一页，修改品牌应该留在当前页面
                  this.getPageList(this.tmForm.id ? this.page : 1);
            }
          }else{
            console.log("error submit!!");
            return false;
          }  
      })
    },
    
     //修改某一个品牌
    updateBrand(row) {
       //row：当前用户选中这个品牌信息
       //显示对话框
       this.dialogFormVisible = true;
       //将已有的品牌信息赋值给tmForm进行展示
       //将服务器返回品牌的信息，直接赋值给了tmForm进行展示。
       //也就是tmForm存储即为服务器返回品牌信息
       this.tmForm = { ...row };
    },
    //删除品牌
    deleteBrand(row){
      //弹出框
      this.$confirm(`你确定删除${row.tmName}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })  
      .then(async () => {
          //当用户点击确定按钮的时候会触发
          //向服务器发请求
          let result = await this.$API.brand.reqDeleteBrand(row.id);
          //如果删除成功
          if (result.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //再次获取品牌列表数据
            this.getPageList(this.list.length>1?this.page:this.page-1);
          }
        })
        .catch(() => {
          //当用户点击取消按钮的时候会触发
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });   
    }

  }
}
</script>





<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
